// @Title  modbus_server.go
// @Description 用来获取设备点表
// @Author  IT搬运工
// @Update
package server

import (
	"intelligentgateway/src/dao"
	"intelligentgateway/src/logs"
	"sort"
	"strconv"
)

//点表项
type Item struct {
	BaseAddr      int      //基础地址
	Quantity      int      //数量
	Keys          []string //名称
	Magnification []int    //倍率
}

//Modbus 点表具体信息
type ModbusPoint struct {
	CollectInterval int    //采集间隔（S）
	Items           []Item //点表具体信息
}

//获取设备上报的数据类型
func GetDataTypeBySn(sn string) []dao.ModbusDataPoint {
	dbConn := dao.GetDB()
	if nil == dbConn {
		return nil
	}
	var dataPoints []dao.ModbusDataPoint
	dbConn.Where("sn=?", sn).Find(&dataPoints)
	return dataPoints
}

//通过指定设备获取点表信息
func GetPointsBySn(sn string, dataType int) *ModbusPoint {
	dbConn := dao.GetDB()
	if nil == dbConn {
		return nil
	}

	//获取设备的详细信息
	var dataPoint dao.ModbusDataPoint
	if dbConn.Where("sn=? AND data_type=?", sn, dataType).First(&dataPoint).RecordNotFound() {
		logs.Debug("Search Fail: sn=%s,data_Type=%d", sn, dataType)
		return nil
	}

	var modbusDataPointItem []dao.ModbusDataPointItem
	if dbConn.Where("point_id=?", dataPoint.Id).Find(&modbusDataPointItem).RecordNotFound() {
		logs.Debug("Search Fail: sn=%s,data_Type=%d,Point_id=%d", sn, dataType, dataPoint.Id)
		return nil
	}
	//排序
	sort.Slice(modbusDataPointItem, func(i, j int) bool {
		return modbusDataPointItem[i].Addr < modbusDataPointItem[j].Addr
	})

	modbusPoint := ModbusPoint{}
	modbusPoint.CollectInterval = dataPoint.CollectInterval

	item := Item{}
	for i, mdpi := range modbusDataPointItem {
		if i == 0 {
			item.BaseAddr = mdpi.Addr
			item.Quantity += 1
			item.Keys = append(item.Keys, mdpi.Key+"#"+strconv.Itoa(mdpi.SerialNum))
			item.Magnification = append(item.Magnification, mdpi.Magnification)
			continue
		}
		//不连续
		if item.BaseAddr+item.Quantity != mdpi.Addr {
			modbusPoint.Items = append(modbusPoint.Items, item)
			//重新赋值
			item = Item{}
			item.BaseAddr = mdpi.Addr
			item.Quantity += 1
			item.Keys = append(item.Keys, mdpi.Key+"#"+strconv.Itoa(mdpi.SerialNum))
			item.Magnification = append(item.Magnification, mdpi.Magnification)
		} else {
			//连续的
			item.Quantity += 1
			item.Keys = append(item.Keys, mdpi.Key+"#"+strconv.Itoa(mdpi.SerialNum))
			item.Magnification = append(item.Magnification, mdpi.Magnification)
		}

	}
	modbusPoint.Items = append(modbusPoint.Items, item)

	return &modbusPoint
}

//获取采集端TCP配置信息
func GetModbusTcpConfig() []dao.GatherTcpInfo {
	dbConn := dao.GetDB()

	var tcpInfoList []dao.GatherTcpInfo
	dbConn.Where("state == ? AND type == ?", 0, 0).Find(&tcpInfoList)
	return tcpInfoList
}

//获取采集端串口配置信息
func GetModbusSerialPortConfig() []dao.GatherSerailPortInfo {
	dbConn := dao.GetDB()

	var serialPortInfoList []dao.GatherSerailPortInfo
	dbConn.Where("state == ? AND type == ?", 0, 0).Find(&serialPortInfoList)
	return serialPortInfoList
}
